/**
 * desc：项目工程复用
 * author：王文军
 * date：  2022/5/9 下午11:47
 */
"use strict";
const Controller = require("egg").Controller;
const mongo = require("../utils/mongo");
const OSS = require("../models/OSS");
const config = require("../../config/db");
const { success, failed } = require("../utils/request");

class ProjectController extends Controller {
  // 获取项目/组件的代码模板
  async getTemplate() {
    const { ctx } = this;
    ctx.body = await mongo().query("project");
  }

  async addTemplate() {
    const { ctx } = this;
    try {
      const info = await mongo().find("project", {
        npmName: ctx.request.body.npmName,
      });
      if (info.length > 0) {
        return (ctx.body = failed("该模板已存在！"));
      }
      const res = await mongo().insert("project", ctx.request.body);
      if (res.result.ok) {
        return (ctx.body = success("添加成功！"));
      }
      ctx.body = failed("添加失败，请稍后重试！");
    } catch (e) {
      ctx.body = failed("系统出错，请稍后重试！");
    }
  }

  async getOSSProject() {
    const { ctx } = this;
    let ossProjectType = ctx.query.type;
    const ossProjectName = ctx.query.name;
    if (!ossProjectName) {
      ctx.body = failed("项目名称不存在");
      return;
    }
    if (!ossProjectType) {
      ossProjectType = "prod";
    }
    let oss;
    if (ossProjectType === "prod") {
      oss = new OSS(config.OSS_PROD_BUCKET);
    } else {
      oss = new OSS(config.OSS_DEV_BUCKET);
    }
    if (oss) {
      const fileList = await oss.list(ossProjectName);
      if (fileList && fileList.length > 0) {
        ctx.body = success("获取项目文件成功", fileList);
      } else {
        ctx.body = success("获取项目文件成功");
      }
    } else {
      ctx.body = failed("获取项目文件失败");
    }
  }

  async getOSSFile() {
    const { ctx } = this;
    const dir = ctx.query.name;
    const file = ctx.query.file;
    let ossProjectType = ctx.query.type;
    if (!dir || !file) {
      ctx.body = failed("请提供OSS文件名称");
      return;
    }
    if (!ossProjectType) {
      ossProjectType = "prod";
    }
    let oss;
    if (ossProjectType === "prod") {
      oss = new OSS(config.OSS_PROD_BUCKET);
    } else {
      oss = new OSS(config.OSS_DEV_BUCKET);
    }
    if (oss) {
      const fileList = await oss.list(dir);
      const fileName = `${dir}/${file}`;
      const finalFile = fileList.find((item) => item.name === fileName);
      ctx.body = success("获取项目文件成功", finalFile);
    } else {
      ctx.body = failed("获取项目文件失败");
    }
  }

  async getRedis() {
    const { ctx, app } = this;
    const { key } = ctx.query;
    if (key) {
      const value = await app.redis.get(key);
      ctx.body = `redis[${key}]:${value}`;
    } else {
      ctx.body = "请提供参数key";
    }
  }
}

module.exports = ProjectController;
